<template>
  <div class="json-formatter">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="input-card">
          <template #header>
            <div class="card-header">
              <span>输入 JSON</span>
              <el-button type="primary" @click="formatJson">格式化</el-button>
            </div>
          </template>
          <el-input
            v-model="inputJson"
            type="textarea"
            :rows="20"
            placeholder="请输入需要格式化的 JSON"
            @paste="handlePaste"
          />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="output-card">
          <template #header>
            <div class="card-header">
              <span>格式化结果</span>
              <el-button type="primary" @click="copyResult">复制结果</el-button>
            </div>
          </template>
          <pre class="json-output" v-html="highlightedJson"></pre>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import hljs from 'highlight.js/lib/core'
import json from 'highlight.js/lib/languages/json'
import 'highlight.js/styles/github.css'

// 注册 JSON 语言高亮
hljs.registerLanguage('json', json)

const inputJson = ref('')
const outputJson = ref('')

const highlightedJson = computed(() => {
  if (!outputJson.value) return ''
  return hljs.highlight(outputJson.value, { language: 'json' }).value
})

const formatJson = () => {
  try {
    // 尝试解析输入的 JSON
    const parsed = JSON.parse(inputJson.value)
    // 格式化 JSON 并保存结果
    outputJson.value = JSON.stringify(parsed, null, 2)
    ElMessage.success('格式化成功')
  } catch (error) {
    ElMessage.error('无效的 JSON 格式')
  }
}

const copyResult = async () => {
  try {
    await navigator.clipboard.writeText(outputJson.value)
    ElMessage.success('复制成功')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const handlePaste = (event) => {
  // 自动格式化粘贴的内容
  setTimeout(formatJson, 0)
}
</script>

<style scoped>
.json-formatter {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-card,
.output-card {
  height: 100%;
}

.json-output {
  margin: 0;
  padding: 14px;
  min-height: 500px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
  overflow: auto;
}

:deep(.el-textarea__inner) {
  font-family: monospace;
  min-height: 500px !important;
}
</style> 